package com.js.sys.fragment.view.first;

import android.app.Service;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.js.lib_common.base.MvpFragment;
import com.js.lib_common.event.StartBrotherEvent;
import com.js.lib_common.mvp.model.response.BindBean;
import com.js.lib_common.mvp.model.response.ProcessMsgBean;
import com.js.lib_common.mvp.model.response.ProdyctInfoResponse;
import com.js.lib_common.mvp.presenter.BindingPresenter;
import com.js.lib_common.mvp.view.BindingView;
import com.js.sys.BaseApplication;
import com.js.sys.R;
import com.js.sys.adapter.BindingAdapter;
import com.js.sys.greendao.db.BindingHistory;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 绑定，
 * 1.产品模式，工序、物料必填(可多选)，整机码选填
 * 2.关联模式，物料必填(可多选)，整机码必填(单个)
 * Created by wz on 2021/5/19.
 */
public class BindFragment extends MvpFragment<BindingPresenter> implements BindingView {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;
    @BindView(R.id.rcy_list)
    RecyclerView rcyList;
    @BindView(R.id.rg_dealWay)
    RadioGroup rgDealWay;
    @BindView(R.id.edt_gx)
    EditText edtGx;
    @BindView(R.id.ll_gx)
    LinearLayout llGx;
    private BindingAdapter mAdapter;
    private static final int DEFAULT_VIEW = 0x22;

    private int bindType = 1;
    private String processCode = "";//选择的工序

    private boolean isHasmachineID = false;

    public static BindFragment newInstance() {
        Bundle args = new Bundle();
        BindFragment fragment = new BindFragment();
        fragment.setArguments(args);
        return fragment;

    }

    @Override
    protected BindingPresenter createPresenter() {
        return new BindingPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tab_first_bind;
    }

    @Override
    protected void initView() {
        mvpPresenter.getAllProductInfo(BaseApplication.userId);
        EventBus.getDefault().register(this);
        toolbarTitle.setText(R.string.tab_first);
        mAdapter = new BindingAdapter(_mActivity, null);
        initRecyclerView(rcyList, mAdapter, 1);
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.im_del) {
                    //删除有整机ID的
                    BindBean bean = mAdapter.getData().get(position);
                    if (bean.getMaterialIdInfo() != null && bean.getMaterialIdInfo().getCurrentBindingMachineId() != null) {
                        machineID = "";
                        isHasmachineID = false;
                    }
                    mAdapter.getData().remove(position);
                    mAdapter.notifyDataSetChanged();


                }
            }
        });

        toolbar.inflateMenu(R.menu.menu_history);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                EventBus.getDefault().post(new StartBrotherEvent(BindHistoryFragment.newInstance(BindBean.REQUEST_CODE_BIND)));


//                pvOptions.show();
                return false;
            }
        });

        rgDealWay.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i) {
                    case R.id.rb_1:
                        llGx.setVisibility(View.VISIBLE);
                        bindType = 1;
                        break;
                    case R.id.rb_2:
                        llGx.setVisibility(View.GONE);
                        bindType = 2;
                        processCode = "";
                        edtGx.setText("");
                        break;
                }
            }
        });
    }

    /**
     * 接收扫码后的信息
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveQrcode(BindBean bean) {
        if (bean.getType() != BindBean.REQUEST_CODE_BIND) {
            return;
        }
        if (mAdapter.getData().contains(bean)) {
            showTips("该项已存在", "请不要重复扫码");
            return;
        }

        String qrcode = bean.getQrcode();
        if (qrcode.contains("WL")) {    //物料
            mvpPresenter.checkMaterialId(BaseApplication.userId, qrcode);
        } else { // 整机
            mvpPresenter.checkMachineId(BaseApplication.userId, qrcode);
        }
        Vibrator vibrator = (Vibrator) _mActivity.getSystemService(Service.VIBRATOR_SERVICE);
        if (vibrator != null)
            vibrator.vibrate(300);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    private String machineID;
    private StringBuilder materialIDs;

    @OnClick({R.id.rl_scan, R.id.rl_clear, R.id.rl_save, R.id.edt_gx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.edt_gx:
                if (pvOptions != null)
                    pvOptions.show();
                break;
            case R.id.rl_scan:
                scan(DEFAULT_VIEW, BindBean.REQUEST_CODE_BIND);
                break;
            case R.id.rl_clear:
                new XPopup.Builder(_mActivity)
                        .asConfirm("清空列表", "确认清空?",
                                "取消", "确定",
                                new OnConfirmListener() {
                                    @Override
                                    public void onConfirm() {
                                        mAdapter.getData().clear();
                                        mAdapter.notifyDataSetChanged();
                                        machineID = "";
                                        isHasmachineID = false;
                                    }
                                }, null, false).show();


                break;
            case R.id.rl_save:
                List<BindBean> list = mAdapter.getData();
                if (list.size() == 0)
                    return;


                materialIDs = new StringBuilder();// 物料id字符串，用英文逗号分隔
//                参数bindType：1工序 2关联
//                选择工序时，物料Id、工序编码必须，整机Id可选；选择关联时，物料Id、整机Id必须

                for (BindBean bindBean : list) {
                    String qrcode = bindBean.getQrcode();
                    if (qrcode.contains("WL")) {    //物料
                        materialIDs.append(qrcode).append(";");
                    } else { // 整机
                        machineID = qrcode;
                    }
                }
                if (materialIDs.length() > 0)
                    materialIDs = materialIDs.deleteCharAt(materialIDs.length() - 1);

                if (materialIDs.length() == 0) {
                    toastShow("请扫描物料编码");
                    return;
                }
                if (bindType == 1) {
                    if (processCode.isEmpty()) {
                        toastShow("请选择工序");
                        return;
                    }
                } else {
                    if (machineID == null || machineID.isEmpty()) {
                        toastShow("请扫描整机码");
                        return;
                    }
                }


                BasePopupView popupView = new XPopup.Builder(_mActivity)
                        .asConfirm("提交", "所需的物料已经完整录入？",
                                "取消", "确定",
                                () -> mvpPresenter.bind(BaseApplication.userId, machineID, materialIDs.toString(), processCode, bindType), null, false);
                popupView.show();


                break;
        }

    }


    @Override
    public void onSuccess(BindBean bean) {
        if (bean.getType() == BindBean.REQUEST_CODE_BIND_MACHINEID) {
            if (isHasmachineID) {
                showTips("无法添加", "物料已绑定整机，不允许同时存在多个整机码");
                return;
            }
            for (BindBean datum : mAdapter.getData()) {
                if (datum.getType() == BindBean.REQUEST_CODE_BIND_MACHINEID) {
                    showTips("错误", "整机码已存在，不允许同时存在多个");
                    return;
                }
            }
        }


        if (!mAdapter.getData().contains(bean))
            mAdapter.addData(bean);

        if (bean.getType() == BindBean.REQUEST_CODE_BIND_MATERIALID) {

            if (bean.getMaterialIdInfo().getCurrentBindingMachineId() != null
                    && !bean.getMaterialIdInfo().getCurrentBindingMachineId().isEmpty()) {
                isHasmachineID = true;
                machineID = bean.getMaterialIdInfo().getCurrentBindingMachineId();
                new XPopup.Builder(_mActivity)
                        .asConfirm("提示", "该物料已绑定整机码，无需再扫码整机码",
                                "取消", "确定",
                                null, null, true).show();
            }
        }


    }


    @Override
    public void onBindSuccess() {
        showTips("绑定成功", "");
        BindingHistory.insertHistory(mAdapter.getData(), true, BindBean.REQUEST_CODE_BIND, "onSuccess");
        machineID = "";
        isHasmachineID = false;
        mAdapter.getData().clear();
        mAdapter.notifyDataSetChanged();
    }

    private ArrayList<ProdyctInfoResponse> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<ProcessMsgBean>> options2Items = new ArrayList<>();

    @Override
    public void getProductInfoSuccess(List<ProdyctInfoResponse> infos) {
        if (infos.size() == 0)
            return;
        options1Items.addAll(infos);
        for (ProdyctInfoResponse info : infos) {
            ArrayList<ProcessMsgBean> list = new ArrayList<>(info.getProcessMsgList());
            options2Items.add(list);
        }
        initOptionPicker();
    }

    @Override
    public void onFailed(String message) {
        showTips("绑定失败", message);
        BindingHistory.insertHistory(mAdapter.getData(), false, BindBean.REQUEST_CODE_BIND, message);
    }

    private OptionsPickerView pvOptions;

    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */

        pvOptions = new OptionsPickerBuilder(_mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1).getPickerViewText() + "-"
                        + options2Items.get(options1).get(options2).getProcessName();
                /* + options3Items.get(options1).get(options2).get(options3).getPickerViewText()*/
                edtGx.setText(tx);
                processCode = options2Items.get(options1).get(options2).getProcessCode();
            }
        })
                .setTitleText("工序选择")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
//                .setSelectOptions(0, 0//默认选中项


                .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
//                .setLabels("产品", "工序", "区")
                .setOutSideColor(0x00000000) //设置外部遮罩颜色
                .setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
                    @Override
                    public void onOptionsSelectChanged(int options1, int options2, int options3) {
//                        String str = "options1: " + options1 + "\noptions2: " + options2 + "\noptions3: " + options3;
//                        Toast.makeText(_mActivity, str, Toast.LENGTH_SHORT).show();
                    }
                })
                .build();

//        pvOptions.setSelectOptions(1,1);
//        /*pvOptions.setPicker(options1Items);//一级选择器*/
//        pvOptions.setPicker(options1Items);
        pvOptions.setPicker(options1Items, options2Items);//二级选择器
        /*pvOptions.setPicker(options1Items, options2Items,options3Items);//三级选择器*/
    }


}
